<template>

  <view class="uni-header">
    <uni-stat-breadcrumb class="uni-stat-breadcrumb-on-phone" />
  </view>

  <view class="uni-container">
    <uni-forms :rules="rules" class="uni-forms" ref="form" :modelValue="formData" validateTrigger="bind">
      <uni-forms-item name="pid" label="所属菜单" required>
        <uni-data-select v-model="formData.pid" :localdata="menuList" :clear="false" />
      </uni-forms-item>

      <uni-forms-item name="title" label="菜单名称" required>
        <uni-easyinput placeholder="请输入菜单名称" v-model="formData.title" trim="both" :clearable="false" />
      </uni-forms-item>
      <uni-forms-item name="type" label="菜单类型" required>
        <uni-data-select v-model="formData.type" :localdata="typeList" :clear="false" />
        <view class="uni-form-item-tips">
          显示的菜单类型：分组、菜单页面、菜单外链<br>
          不显示的菜单类型：页面
        </view>
      </uni-forms-item>

      <uni-forms-item v-show="formData.type != 'page'" name="icon" label="菜单图标">
        <view style="display:flex;flex-direction: column;">
          <view>
            <uni-easyinput placeholder="可自定义或使用系统图标" v-model="formData.icon" trim="both" :clearable="false" />
          </view>
          <unify-icons-picker v-model="formData.icon" />
        </view>
        <view class="uni-form-item-tips">
          可直接填写图标URL
        </view>
      </uni-forms-item>
      <view v-if="formData.type != 'group'">
        <uni-forms-item name="url" label="菜单链接" required>
          <uni-combox :candidates="pages" placeholder="请严格按照参考格式填写" v-model="formData.url"></uni-combox>
          <view class="uni-form-item-tips">
            <view>菜单格式：页面地址，例如：/pages/unify/user/list，<text style="color:red;">请留意大小写</text></view>
            <view>外链格式：swagger/index，未包含http或https默认拼接接口域名({{$env.PROJECT_API_BASE_URL}})。</view>
          </view>
        </uni-forms-item>
        <uni-forms-item name="param" label="扩展参数">
          <uni-easyinput placeholder="请严格按照参考格式填写" v-model="formData.param" trim="both" :clearable="false" />
          <view class="uni-form-item-tips">
            选填，参考格式：a=123&b=345，插件格式：_p=插件名称&_c=插件控制器&_a=插件方法
          </view>
        </uni-forms-item>
        <uni-forms-item class="flex-center-x" name="target" label="打开方式" required>
          <uni-data-select v-model="formData.target" :localdata="targetList" :clear="false" />
        </uni-forms-item>
        <uni-forms-item name="debug" label="开发模式" required>
          <uni-data-checkbox v-model="formData.debug" :localdata="debugList" />
          <view class="uni-form-item-tips">
            是：仅开发模式可见该菜单。
          </view>
        </uni-forms-item>

        <uni-forms-item class="flex-center-x" name="authList" label="关联权限" required>
          <uni-data-checkbox multiple v-model="formData.authList" :localdata="authList"></uni-data-checkbox>
        </uni-forms-item>
      </view>
      <uni-forms-item class="flex-center-x" name="status" label="菜单状态" required>
        <uni-data-checkbox v-model="formData.status" :localdata="statusList" />
      </uni-forms-item>
      <uni-forms-item name="serial" label="排序号" required>
        <uni-easyinput type="number" placeholder="请输入排序号" v-model="formData.serial" trim="both" :clearable="false" />
      </uni-forms-item>
      
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;"
          @click="submitForm">{{$t('common.button.submit')}}</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>

  <fix-window />
</template>

<script>
  import {
    mapActions
  } from 'vuex'
  import {
    pages
  } from "@/pages.json"
  export default {
    data() {
      return {
        rules: {
          pid: {
            rules: [{
              required: true,
              errorMessage: "请指定所属菜单"
            }]
          },
          title: {
            rules: [{
                required: true,
                errorMessage: "请指定标题"
              },
              {
                minLength: 2,
                maxLength: 20,
                errorMessage: '标题长度在 {minLength} 到 {maxLength} 个字符',
              }
            ]
          },
          serial: {
            rules: [{
              required: true,
              errorMessage: "请指定排序号"
            }]
          },
        },
        pages: [],
        targetList: [],
        typeList: [],
        statusList: [],
        menuList: [],
        debugList: [],
        formData: {},
      }
    },

    onLoad(params) {
      this.pages = pages.map(item => "/" + item.path);
      this.buildPage(params)
    },
    methods: {
      ...mapActions({
        getMenuForm: "menu/form",
        saveMenu: "menu/save",
        userInit: "user/init",
      }),
      async buildPage(params = {}) {
        uni.showLoading({
          mask: true,
        })

        let data = await this.getMenuForm(params);


        this.targetList = [];
        Object.keys(data.targetList).forEach(key => {
          this.targetList.push({
            value: key,
            text: data.targetList[key]
          });
        });


        this.statusList = [];
        Object.keys(data.statusList).forEach(key => {
          this.statusList.push({
            value: parseInt(key),
            text: data.statusList[key]
          });
        });


        this.typeList = [];
        Object.keys(data.typeList).forEach(key => {
          this.typeList.push({
            value: key,
            text: data.typeList[key]
          });
        });


        this.debugList = [];
        Object.keys(data.debugList).forEach(key => {
          this.debugList.push({
            value: parseInt(key),
            text: data.debugList[key]
          });
        });

        this.menuList = [{
          value: 0,
          text: "顶级菜单"
        }];
        data.menuList.forEach(menu => {
          this.menuList.push({
            value: menu.id,
            text: menu.title
          });
        });


        data.authList.map(item => {
          item.text = item.name;
          item.value = item.id;
        });
        this.authList = data.authList;


        this.formData = data.entity;

        uni.hideLoading()
      },
      submitForm() {
        uni.showLoading({
          mask: true
        })

        this.$refs.form.validate().then(data => {

          data.id = this.formData.id || 0;
          this.saveMenu(data).then(res => {
            this.userInit()

            uni.showModal({
              title: "提示",
              content: "操作成功",
              confirmText: "返回",
              cancelText: "继续添加",
              showCancel: !this.formData.id,
              success: (e) => {
                if (!e.cancel) {
                  this.back()
                } else {
                  this.buildPage()
                }
              }
            })
          }).finally(_ => {
            uni.hideLoading()
          })
        }).catch(() => {
          uni.hideLoading()
        })
      },
    }
  }
</script>